package com.haierp.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Sets;
import com.haierp.exception.ErpCommonException;
import com.haierp.exception.InventoryException;
import com.haierp.mapper.InventoryOutDetailMapper;
import com.haierp.mapper.InventoryOutMapper;
import com.haierp.model.InventoryArea;
import com.haierp.model.InventoryOut;
import com.haierp.model.InventoryOutDetail;
import com.haierp.service.IErpOrderService;
import com.haierp.service.IInventoryAreaService;
import com.haierp.service.IInventoryOutService;
import com.haierp.service.IInventoryService;
import com.haierp.util.JsonPageResult;
import com.haierp.vo.InventoryOutVO;

@Service("inventoryOutService")
public class InventoryOuServicetImpl extends SuperServiceImpl<InventoryOutMapper, InventoryOut> implements IInventoryOutService {
	protected Logger logger = LogManager.getLogger(getClass());
	
	@Autowired
	private InventoryOutDetailMapper inventoryOutDetailMapper;
	@Autowired
	private IInventoryService inventoryService;
	@Autowired
	private IInventoryAreaService inventoryAreaService;
	@Autowired
	private IErpOrderService erpOrderService;
	
	@Override
	public void addInventoryOut(InventoryOut inventoryOut) {
		this.baseMapper.insert(inventoryOut);
		
		List<InventoryOutDetail> inventoryOutDetailList = inventoryOut.getInventoryOutDetailList();
		inventoryOutDetailList.forEach(inventoryOutDetail -> {
			inventoryOutDetail.setInventoryOutId(inventoryOut.getId());
		});
		inventoryOutDetailMapper.insertBatch(inventoryOutDetailList);
	}
	
	@Override
	public void updateInventoryOut(InventoryOut inventoryOut) {
		this.baseMapper.updateSelectiveById(inventoryOut);
		
		List<InventoryOutDetail> inventoryOutDetailList = inventoryOut.getInventoryOutDetailList();
		List<InventoryOutDetail> inventoryOutDetailListNew = new ArrayList<>(); //新增的SKU
		List<InventoryOutDetail> inventoryOutDetailListUpdate = new ArrayList<>();//修改的SKU
		
		//获取数据库里面的所有sku
		InventoryOut inventoryOutDb = queryInventoryOut(inventoryOut.getId());
		List<InventoryOutDetail> inventoryOutDetailListDb = inventoryOutDb.getInventoryOutDetailList();
		Set<Long> allInventoryOutDetailId = new HashSet<Long>();
		if(inventoryOutDetailListDb!=null && !inventoryOutDetailListDb.isEmpty()){
			inventoryOutDetailListDb.forEach(inventoryOutDetail->{ allInventoryOutDetailId.add(inventoryOutDetail.getId()); });
		}
		inventoryOutDetailList.forEach(inventoryOutDetail -> {
			if(inventoryOutDetail.getId()==null){
				inventoryOutDetail.setInventoryOutId(inventoryOut.getId());
				inventoryOutDetailListNew.add(inventoryOutDetail);
			} else {
				if(!allInventoryOutDetailId.isEmpty()){
					allInventoryOutDetailId.remove(inventoryOutDetail.getId());
				}
				inventoryOutDetail.setInventoryOutId(inventoryOut.getId());
				inventoryOutDetailListUpdate.add(inventoryOutDetail);
			}
		});
		if(!inventoryOutDetailListUpdate.isEmpty()) {
			inventoryOutDetailMapper.updateBatchById(inventoryOutDetailListUpdate);
		}
		if(!inventoryOutDetailListNew.isEmpty()) {
			inventoryOutDetailMapper.insertBatch(inventoryOutDetailListNew);
		}
		if(!allInventoryOutDetailId.isEmpty()){
			inventoryOutDetailMapper.deleteBatchIds(new ArrayList<Long>(allInventoryOutDetailId));
		}
	}
	
	@Override
	public InventoryOut queryInventoryOut(Long inventoryOutId) {
		if(inventoryOutId==null){
			throw new RuntimeException("the item id is null");
		}
		InventoryOut inventoryOut = this.baseMapper.selectById(inventoryOutId);
		if(inventoryOut != null) {
			EntityWrapper<InventoryOutDetail> entityWrapper = new EntityWrapper<InventoryOutDetail>();
			entityWrapper.where("inventory_out_id={0}", inventoryOutId);
			
			List<InventoryOutDetail> inventoryOutDetailList = inventoryOutDetailMapper.selectList(entityWrapper);
			if(inventoryOut != null){
				inventoryOut.setInventoryOutDetailList(inventoryOutDetailList);
			}
		}
		return inventoryOut;
	}
	
	@Override
	public JsonPageResult<List<InventoryOut>> inventoryOutQueryList(InventoryOutVO inventoryOutVO) {
		JsonPageResult<List<InventoryOut>> taskDailyResult = new JsonPageResult<>();
		//1、查询总的记录数量
		Integer totalCount =  baseMapper.queryInventoryOutCount(inventoryOutVO);
		
		//2、查询分页记录
		if(totalCount!=null&&totalCount!=0L){
			taskDailyResult.buildPage(totalCount, inventoryOutVO);
			List<InventoryOut> inventoryOuts = baseMapper.queryInventoryOutList(inventoryOutVO);
			taskDailyResult.setData(inventoryOuts);
		}
		return taskDailyResult;
	}
	
	@Override
	public Set<Long> addInventoryOutConfirm(InventoryOut inventoryOut) {
		//添加出库单
		this.addInventoryOut(inventoryOut);
		//库存出库
		return this.inventoryCheckOutBatch(inventoryOut);
	}
	
	@Override
	public Set<Long> updateInventoryOutConfirm(InventoryOut inventoryOut) {
		//修改出库单
		this.updateInventoryOut(inventoryOut);
		//库存出库
		return this.inventoryCheckOutBatch(inventoryOut);
	}
	
	@Override
	public Set<Long> inventoryCheckOutBatch(InventoryOut inventoryOut) {
		Set<Long> skuIdSet = Sets.newHashSet();
		List<InventoryOutDetail> inventoryOutDetailList = inventoryOut.getInventoryOutDetailList();
		inventoryOutDetailList.forEach(inventoryOutDetail -> {
			Long inventoryAreaId = inventoryOutDetail.getInventoryAreaId();
			Integer quantity = inventoryOutDetail.getQuantity();
			if (inventoryOutDetail.getInventoryAreaId()== null || inventoryOutDetail.getQuantity() == null) {
				throw new ErpCommonException("有空数据");
			} else {
				if (inventoryOutDetail.getQuantity() <= 0) {
					throw new ErpCommonException("减少的库存要为正数");
				}
				try {
					inventoryService.inventoryCheckOut(inventoryAreaId, quantity, "批量出库");
				} catch (InventoryException e) {
					logger.info("批量出库异常 inventoryOutId：" + inventoryOut.getId() + " inventoryAreaId：" + inventoryAreaId, e);
					return;
				}
				skuIdSet.add(inventoryOutDetail.getSkuId());
			}
		});
		return skuIdSet;
	}

	@Override
	public void deleteInventoryOutById(Long id) {
		InventoryOut inventoryOut = this.baseMapper.selectById(id);
		if(inventoryOut.getStatus() != 0) {
			throw new ErpCommonException("已出库状态不能删除");
		}
		this.baseMapper.deleteById(id);
		
		InventoryOutDetail inventoryOutDetail = new InventoryOutDetail();
		inventoryOutDetail.setInventoryOutId(id);
		inventoryOutDetailMapper.deleteSelective(inventoryOutDetail);
	}

}
